package com.lxmes.gs.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.gs.domain.CostSummary;
import com.lxmes.gs.service.ICostSummaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;

import javax.validation.Validator;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxmes.gs.mapper.CostListMapper;
import com.lxmes.gs.domain.CostList;
import com.lxmes.gs.service.ICostListService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 成本清单Service业务层处理
 *
 * @author wdf
 * @date 2023-04-24
 */
@Service
public class CostListServiceImpl extends ServiceImpl<CostListMapper, CostList> implements ICostListService {

    @Autowired
    private CostListMapper costListMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ICostSummaryService costSummaryService;

    /**
     * 查询成本清单
     *
     * @param id 成本清单主键
     * @return 成本清单
     */
    @Override
    public CostList selectCostListById(Long id) {
        return costListMapper.selectById(id);
    }

    /**
     * 查询成本清单列表
     *
     * @param costList 成本清单
     * @return 成本清单
     */
    @Override
    public List<CostList> selectCostListList(CostList costList) {
        return costListMapper.selectList(Wrappers.lambdaQuery(costList));
    }

    /**
     * 新增成本清单
     *
     * @param costList 成本清单
     * @return 结果
     */
    @Override
    public int insertCostList(CostList costList) {
        String certificateCode = StrUtil.format("PZ{}{}" , DateUtil.format(new Date(), "yyyyMMdd"), NumberUtil.decimalFormat("000" , RandomUtil.randomInt(1, 1000)));
        costList.setCertificateCode(certificateCode);
        costList.setDocumentPerson(SecurityUtils.getUsername());
        costList.setDocumentTime(new Date());
        return costListMapper.insert(costList);
    }

    /**
     * 修改成本清单
     *
     * @param costList 成本清单
     * @return 结果
     */
    @Override
    public int updateCostList(CostList costList) {
        return costListMapper.updateById(costList);
    }

    /**
     * 批量删除成本清单
     *
     * @param ids 需要删除的成本清单主键
     * @return 结果
     */
    @Override
    public int deleteCostListByIds(Long[] ids) {
        return costListMapper.deleteCostListByIds(ids);
    }

    /**
     * 删除成本清单信息
     *
     * @param id 成本清单主键
     * @return 结果
     */
    @Override
    public int deleteCostListById(Long id) {
        return costListMapper.deleteById(id);
    }

    @Override
    public String imporIteminfo(List<CostList> costListList, boolean updateSupport) {
        if (StringUtils.isNull(costListList) || costListList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CostList costList : costListList) {
            try {
                BeanValidators.validateWithException(validator, costList);
                this.insertCostList(costList);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditCostList(Long[] ids) {
        List<CostList> costLists = baseMapper.selectBatchIds(Arrays.asList(ids));
        if (costLists.stream().anyMatch(i -> StringUtils.equals(i.getAudit(), "1"))) {
            throw new ServiceException("存在已审核数据，操作失败");
        }
        costLists.forEach(i -> i.setAudit("1"));
        this.updateBatchById(costLists);
        for (CostList costList : costLists) {
            CostSummary costSummary = costSummaryService.getOne(Wrappers.lambdaQuery(CostSummary.class).eq(CostSummary::getProjectCode, costList.getProjectCode()));
            if (ObjectUtil.isNull(costSummary)) {
                costSummary = new CostSummary();
                costSummary.setProjectCode(costList.getProjectCode());
                costSummary.setProjectName(costList.getProjectName());
                costSummary.setSummaryType("1");
                costSummary.setMaterialCost(0D);
                costSummary.setLaborCost(0D);
                costSummary.setLeasingCost(0D);
                costSummary.setSubcontractingCost(0D);
                costSummary.setIndirectCost(0D);
                costSummary.setTotalCost(0D);
                calculateCost(costList, costSummary);
                costSummaryService.insertCostSummary(costSummary);
            } else {
                calculateCost(costList, costSummary);
                costSummaryService.updateCostSummary(costSummary);
            }
        }
        return 1;
    }

    private void calculateCost(CostList costList, CostSummary costSummary) {
        Double amount = costList.getAmount();
        switch (costList.getCostType()) {
            case "1":
                //材料
                costSummary.setMaterialCost(costSummary.getMaterialCost()+ amount) ;
                break;
            case "2":
                //劳务
                costSummary.setLaborCost(costSummary.getLaborCost()+ amount); ;
                break;
            case "3":
                //租赁
                costSummary.setLeasingCost(costSummary.getLeasingCost() + amount);
                break;
            case "4":
                //分包
                costSummary.setSubcontractingCost(costSummary.getSubcontractingCost()+ amount);
                break;
            case "5":
                //间接
                costSummary.setIndirectCost(costSummary.getIndirectCost()+ amount);
                break;
        }
        costSummary.calculateTotalCost();
    }
}
